﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace StateManager
{
    public class SManagerService : BackgroundService
    {
        SManager _sManager;
        Action<string, string, bool> _logFun;
        /// <summary>
        /// 创建状态机服务
        /// </summary>
        /// <param name="logFun">写日志函数。参数1：模块名；参数2：日志内容；参数3：是否为操作日志。如果为null则使用内置写文件</param>
        /// <param name="eventFun">系统事件回调</param>
        /// <param name="owner">创建者</param>
        /// <param name="paused">创建时暂停，后续手动开启</param>
        /// <param name="projectDir">工作目录</param>
        /// <param name="cfgFileName">主配置文件</param>
        public SManagerService(Action<string, string, bool> logFun = null, Action<SManager, SEventType> eventFun = null, object owner = null, bool paused = false, string projectDir = "./", string jsonFileName = "default.json")
        {
            _logFun = logFun;
            _sManager = new SManager(logFun, eventFun, owner, paused, projectDir, jsonFileName);
        }
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (!stoppingToken.IsCancellationRequested)
            {
                _logFun("系统日志", "SManagerService服务启动成功", false);
            }

            return Task.CompletedTask;
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logFun("系统日志", "SManagerService服务开始停止..", false);
            _sManager.Dispose();
            _logFun("系统日志", "SManagerService服务停止成功", false);
            await base.StopAsync(cancellationToken);
        }

    }
}
